var __autoLoad__;
var __cfphelperDays__;
var __benchmarkRates__;

console.log("chrome.extension:" + chrome.extension);
console.log("chrome.extension.getURL:" + chrome.extension.getURL);
console.log("chrome.extension.getBackgroundPage:" + chrome.extension.getBackgroundPage);
console.log("chrome.tabs:" + chrome.tabs);

function AddAmtRange(randamGen, params) {
	
	var amt = randamGen.integer({min: 5100, max: 5999});
	var h = '<li><a href="/transfer/list?';
	
	var arr = new Array();
	if ( params['sort'] != undefined ) arr.push('sort=' + params['sort']);
	arr.push('amt=-' + amt);
	if ( params['period'] != undefined ) arr.push('period=' + params['period']);
	h += arr.join('&');
	
	if ( params['amt'] != undefined ) {
		var num = parseInt(params['amt']);
		if ( num >= -5999 && num <=-5000) h += '" class="current"';
		else h += '"';
	} else {
		h += '"';
	}
	
	h += '>5k左右</a></li>';
	$("body > div.content.clearfix > div.product_warp > div.product_mod > div.filter_mod > div.attr_group.first > div.attr_value > ul > li:nth-child(2)").before(h);

}

function AddPeriodRange(randamGen, params) {
	
	var h = '<li><a href="/transfer/list?';
	
	var arr = new Array();
	if ( params['sort'] != undefined ) arr.push('sort=' + params['sort']);
	if ( params['amt'] != undefined ) {
		var num = parseInt(params['amt']);
		var amt = 0;
		if ( num >= -5999 && num <=-5000) {
			amt = randamGen.integer({min: 5100, max: 5999});
		} else {
			amt = -num;
		}
		arr.push('amt=-' + amt);
	}
	arr.push('period=90-360');
	h += arr.join('&');
	
	if ( params['period'] == '90-360' ) {
		h += '" class="current"';
	} else {
		h += '" ';
	}
	h += '>90-360天</a></li>';

	console.log(h);
	
	$("body > div.content.clearfix > div.product_warp > div.product_mod > div.filter_mod > div.attr_group.last > div.attr_value > ul > li:nth-child(4)").before(h);
}

function ModifySortArea() {
	var parentContainer = $('body > div.content.clearfix > div.product_warp > div.product_mod > div.sort_mod.J_sort_mod');
	
	// 1. 修改文字描述
	parentContainer.find('dd.current > a').text('智能排序');
	var autoLoad = __autoLoad__;
	// 2. 自动加载分页选项框
	$('<input type="checkbox" name="ChkBoxAutoLoading" checked=false>自动加载分页</input>')
		.appendTo(parentContainer.find('dd:nth-child(2)').html(''))
		.prop('checked', __autoLoad__)
		.change( function()
							{ 
								//localStorage[$(this).attr("name")] = $(this).prop("checked");
								StoreAutoLoading($(this).prop("checked"), function(){
										window.location.reload();
								});
								//window.location.reload();
							} 
						);
	
  // 3. 计划持有日期范围选择框
	var cfphelperDays = __cfphelperDays__;
	$('<input type="range" style="width:55px;height:15px" name="cfphelper_days" min="30" max="100" step="10" value="30"/>')
		.appendTo(parentContainer.find('dd:nth-child(3)').html(''))
		.val( cfphelperDays )
		.after('计划持有<input type="text" style="width:20px;font-size:9px" disabled value='  + cfphelperDays + ' />天')
		.change(function()            
							{
								$(this).next().val($(this).val());
								StorePlanPeriod($(this).val(), function(response){
										GetPlanPeriod(CalcData);
								});
							});
	// 4. 产品统计信息 '<dd>已加载3页，共153个产品</dd>'
	parentContainer.find('dd:nth-child(4)').html('');
	
}

function updateLoadStatistics(loadPageContext) {
	var currentPage;
	
	if ( loadPageContext == undefined ) 
		currentPage = 1;
	else
		var currentPage = loadPageContext.p['page'];
	
	var productAmt = $("body > div.content.clearfix > div.product_warp > div.product_mod > div.pro_list").size();
	$('body > div.content.clearfix > div.product_warp > div.product_mod > div.sort_mod.J_sort_mod')
		.find('dd:nth-child(4)')
		.html('已加载' + currentPage + '页，共' + productAmt + '个产品'
			+ '<a id="filterProducts" class="cfp-icon cfp-icon-filter" href="javascript:void(0)"/>'
			+ '<a id="reloadBenchmarkRates" class="cfp-icon cfp-icon-update-rates" href="javascript:void(0)"/>');
	$('#filterProducts').click(filterProducts);
	$('#reloadBenchmarkRates').click(ReloadBenchmarkRates);
}

function FilterProducts() {
	
}

function CalcData(loadPageContext) {
	var benchmarkRates = __benchmarkRates__;
	var cfphelperDays = __cfphelperDays__;
	$("body > div.content.clearfix > div.product_warp > div.product_mod > div.pro_list").each(function() {
			
			var parentContainer = $(this);
			var currentRate;
			var days;
			
			if (parentContainer.data('productInfoParsed')) {
				currentRate = parentContainer.data('currentRate');
				days = parentContainer.data('remainingMaturity');
			} else {
				var strEndDate = $(this).find("li.last > span.tit").text().replace("预计到期日：","");
				var arr = strEndDate.split("-");
				var endDate = new Date(arr[0], arr[1] - 1, arr[2]);
				var currentRateText = $(parentContainer).find("div.pro_info > ul.pro_buyinfo > li > span.impt").text().split('%')[0];
				currentRate = Number(currentRateText) / 100;
				days = parseInt(Math.abs(endDate.getTime() - new Date().getTime()) / 1000 / 60 / 60 /24);
				$(this).find("li.last > span.tit").text( days + "天，" + strEndDate + "到期" );
			}
			
			FullfillProductInfo(parentContainer, currentRate, days, benchmarkRates);
		}
	);
	
	$("body > div.content.clearfix > div.product_warp > div.product_mod > div.pro_list").sortElements(function(a, b) {
			return $(a).data('totalAnnualizedRateofReturn') < $(b).data('totalAnnualizedRateofReturn') ? 1 : -1;
  });
}

function FullfillProductInfo(parentContainer, currentRate, remainingMaturity, benchmarkInterestRates) {
	var data = CalcBenchmarkInterestRate(currentRate, remainingMaturity, benchmarkInterestRates, __cfphelperDays__);
	if ( data == null) return;
	$(parentContainer)
		.data('margin', data.margin)
		.data('totalInterestMargin', data.totalInterestMargin)
		.data('currentRate', data.currentRate)
		.data('remainingMaturity', data.remainingMaturity)
		.data('productInfoParsed', true)
		.data('totalAnnualizedRateofReturn', data.totalAnnualizedRateofReturn)
		.find("div.pro_info > ul.pro_buyinfo > li:first > span.tit")
		.text(__cfphelperDays__ + '天' + ToDecimal2(data.margin*100) + "%，" 
			+ ToDecimal2(data.totalAnnualizedRateofReturn * 100) + '%');
}

function LoadAll(pageLoadEndCallback, allPageLoadEndCallback) {
  
  var pageInfo = GetPagingInfo(document, '/transfer/list');
	var params = pageInfo.params;
	var maxPage = pageInfo.maxPage;
	var currentPage = pageInfo.currentPage
	
	var loadPageContext = 
		{d:0, p:params, pageLoadEndCallback:pageLoadEndCallback, allPageLoadEndCallback:allPageLoadEndCallback};
	params['page'] = 1;
	if ( !pageInfo.pagingFlag ) {
		
		if ($.isFunction(pageLoadEndCallback)) 
			pageLoadEndCallback(loadPageContext);
		
		if ($.isFunction(allPageLoadEndCallback)) 
			allPageLoadEndCallback(loadPageContext);
		
		return;
		
	}
	params['page'] = 2;
	$.ajax(
		{
			url: '/transfer/list',
			type: 'get',
			data:loadPageContext.p,
			context:loadPageContext,
			beforeSend: function( xhr ) {  xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }}); }, 
			success:  LoadPage
		}); 
}

function LoadPage(data) {
	
	loadPageContext = this;
	var pagingBar = $("body > div.content.clearfix > div.product_warp > div.product_mod > div.pagination_mod.tr");
	var proList = $(data).find('div.product_warp > div.product_mod > div.pro_list').filter(function(index){
			var link = $(this).find('div.pro_side > a');
			var end = link.hasClass('btn_ended');
			return !link.hasClass('btn_ended');
	});
	
	pagingBar.before(proList);
	
	if ($.isFunction(loadPageContext.pageLoadEndCallback)) 
		loadPageContext.pageLoadEndCallback(loadPageContext);
	
	if ( proList.size() == 0 || loadPageContext.p['page']  >= 10) {
		
		if ($.isFunction(loadPageContext.allPageLoadEndCallback)) 
			loadPageContext.allPageLoadEndCallback(loadPageContext);
		
		return;
	}

	loadPageContext.d = loadPageContext.d + 1;
	loadPageContext.p['page'] = loadPageContext.p['page'] + 1;
	
	$.ajax(
		{
			url: '/transfer/list',
			type: 'get',
			data:loadPageContext.p,
			context:loadPageContext,
			beforeSend: function( xhr ) {  xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }}); }, 
			success:  LoadPage
		}); 
}

function GetBenchmarkRatesFromCache(callback) {
	_SendMessage({}, function(response){
			console.log(response.result);
			__benchmarkRates__ = JSON.parse(response.result);
	}, callback);
}

function ReloadBenchmarkRates() {
	_SendMessage({}, function(response){
			__benchmarkRates__ = JSON.parse(response.result);
	}, CalcData);

}

function GetAutoLoading(callback) {
	console.log('In GetAutoLoading')
	_SendMessage({}, function(response){
		__autoLoad__ = (response.result == 'true');
	}, callback);
}

function GetPlanPeriod(callback) {
	console.log('In GetPlanPeriod')
	_SendMessage({}, function(response){
			__cfphelperDays__ = parseInt(response.result);
	}, callback);
}

function StoreAutoLoading(autoLoading, callback) {
	_SendMessage({"AutoLoading": autoLoading}, callback);
}

function StorePlanPeriod(planPeriod, callback) {
	_SendMessage({"PlanPeriod": planPeriod}, callback);
}

function RenderRateTable() {
	console.log('In RenderRateTable');
	_SendMessage({"template": "ratetable"}, function(response) {
			//填充模板，并插入到dom中
			var sidebar = $(response.result);
			$('body > div.content.clearfix > div.product_warp > div.product_side > div:nth-child(1)')
				.before(sidebar);
				
			//获取绘图区域并画出基准收益率
			var benchmarkRates = __benchmarkRates__;
			var chartx = [], charty = [];
			//先填入第一个数据，之后所有填充数据为前开后闭
			chartx.push(benchmarkRates[0].days);
			charty.push(benchmarkRates[0].annualizedRate);
			for(var i = 0; i < (benchmarkRates.length - 1); i++) {
				var rate = benchmarkRates[i];
				// 每日利率增长步长
				var step = benchmarkRates[i+1].perday;
				// 起始天数
				var start = benchmarkRates[i].days;
				// 结束天数
				var end = benchmarkRates[i+1].days;
        // 前开后闭
				for ( var j = start + 1; j <= end; j++) {
					chartx.push(j);
					charty.push((j - start) * step + benchmarkRates[i].annualizedRate);
				}
				
			}
			
			var chartCtx = document.getElementById("rateChart").getContext("2d");
			
			var data = {
				labels: chartx,
				datasets: [{
							label: "",
							fillColor: "rgba(151,187,205,0.2)",
							strokeColor: "rgba(151,187,205,1)",
							pointColor: "rgba(151,187,205,1)",
							pointStrokeColor: "#fff",
							pointHighlightFill: "#fff",
							pointHighlightStroke: "rgba(151,187,205,1)",
							data: charty
						}
					]
			};
			
			var myLineChart = new Chart(chartCtx).Line(data, {
					scaleShowGridLines: false,
					pointDot: false,
					datasetStroke: false,
					animation: true,
					datasetFill: true,
					showTooltips: false,
					scaleLabel: "<%= (Number(value)*100).toFixed(2) + '%'%>",
					scaleFontSize: 9,
					showXLabels: 8, // from https://github.com/hay-wire/Chart.js/tree/skip-xlabels
					//showScale: false,
					labelsFilter: function (value, index) {
						return (index + 1) % 60 != 0;
					}
			});
			
			//计算30天套利空间曲线
			var totalreturny = [], totalreturnx = [];
			for(var x = 120; x <= 690; x++ ) {
				var ratex = GetBenchmarkInterestRate(x, benchmarkRates);
				var rate = GetBenchmarkInterestRate(x-30, benchmarkRates);
				var margin = ratex*1.05 -rate;
				totalreturny.push(margin/30*360+ratex);
				totalreturnx.push(x);
				console.log(x + ',' + (margin/30*360+ratex));
			}
			
			var returnChartCtx = document.getElementById("returnChart").getContext("2d");
			var returnChartData = {
							labels: totalreturnx,
							datasets: [{
										label: "",
										fillColor: "rgba(151,187,205,0.2)",
										strokeColor: "rgba(151,187,205,1)",
										pointColor: "rgba(151,187,205,1)",
										pointStrokeColor: "#fff",
										pointHighlightFill: "#fff",
										pointHighlightStroke: "rgba(151,187,205,1)",
										data: totalreturny
									}
								]
						};
		 var returnChart = new Chart(returnChartCtx).Line(returnChartData, {
					scaleShowGridLines: false,
					pointDot: false,
					datasetStroke: false,
					animation: true,
					datasetFill: true,
					showTooltips: false,
					scaleLabel: "<%= (Number(value)*100).toFixed(2) + '%'%>",
					scaleFontSize: 9,
					showXLabels: 8, // from https://github.com/hay-wire/Chart.js/tree/skip-xlabels
					//showScale: false,
					labelsFilter: function (value, index) {
						return (index + 1) % 60 != 0;
					}
			});
	});
}

// inject code into "the other side" to talk back to this side;
// appending text to a function to convert it's src to string only works in Chrome
// and then hide the evidence as much as possible.
// listen for the message
function DectectLoginStatusAndKeep() {
	
	window.addEventListener("MyCustomEvent", function (e) {
		if ( e.detail.global.userID == undefined ) {
			console.log("用户未登录，无法启动保持在线服务");
			return;
		}
		KeepUserLogin(e.detail.global);
		StartTrader(e.detail.global);
	});
	
	var scr = document.createElement('script');
	
	scr.textContent = '(function () {'
		+ 'var pageGlobal = window.global;'
		+ 'var event = document.createEvent("CustomEvent");'  
		+ 'event.initCustomEvent("MyCustomEvent", true, true, {"global": pageGlobal});'
		+ 'window.dispatchEvent(event);})();'
	console.log('Inject code:');
	console.log(scr.textContent);
	(document.head || document.documentElement).appendChild(scr);
	
	scr.parentNode.removeChild(scr);
	
}

function KeepUserLogin(global) {
	var g_tk = global.csrf.value, platform = global.platform, ajax = 1;
	var intervalId = setInterval(function(){
		$.post("https://www.caifupai.com/my/userMsgCount", 
			{ g_tk: g_tk, platform: platform, ajax:1 },
		 function(data){
		 	 var result = data;
			 console.log(result);
			 if ( result.retCode != 0 ) {
			 	 console.log("用户已断线");
			 	 clearInterval(intervalId);
			 } else {
			 	 console.log("用户保持在线");
			 }
		 });
	}, 1000 * 60 * 3);
}

function StartTrader(global) {
	try {
		trader = new Trader(global);
		console.log(trader);
		trader.loadAllPage();     
	} catch(e) {
		console.log(e);
	}
}

function _SendMessage(context, callback, next) {
	
	if (context.actionCommand == undefined) {
		context.actionCommand = _SendMessage.caller.name;
	}
	
	chrome.runtime.sendMessage(context, function(response){
			
			console.log(response.result);
			
			if(callback == undefined) 
				return
			callback(response);
			
			if (next == undefined) 
				return;
			next();
			
	});
	
}
var __isInListPage__ = ($('body > div.content.clearfix > div.product_warp > div.product_mod').length != 0);
if (__isInListPage__) {
	GetBenchmarkRatesFromCache(function() {
		var seed = Date.parse(new Date()); 
		var randamGen = new Chance(seed);
		var params = GetCFPUrlParms();
		GetAutoLoading(
			function() {
				GetPlanPeriod(function(){
					console.log('call GetPlanPeriod\'s callback')
					ModifySortArea();
					if (__autoLoad__) {
							LoadAll(updateLoadStatistics, CalcData);
						} else {
							updateLoadStatistics();
							CalcData();
						}
					AddAmtRange(randamGen, params);
					AddPeriodRange(randamGen, params);
					RenderRateTable();
					DectectLoginStatusAndKeep();
				});
			}
		);
	});
}
console.log('helper.js loaded');